package com.twq.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.twq.pojo.Role;
import com.twq.pojo.User;
import com.twq.service.role.RoleServiceImpl;
import com.twq.service.user.UserServiceImpl;
import com.twq.util.Constants;
import com.twq.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("savepwd") && method != null){
            this.updatePwd(req,resp);
        }else if (method.equals( "pwdmodify") && method != null){
            this.pwdmodify(req,resp);
        }else if (method.equals( "query")){
            this.query(req,resp);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        从session中拿id
        Object object = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");

        boolean flag =false;
        if (object !=null && newpassword != null){
//使用工具类容易出问题            !StringUtils.isNullOrEmpty(newpassword)
            UserServiceImpl userService = new UserServiceImpl();
            flag = userService.updatePwd(((User)object).getId(),newpassword);

            if (flag){
                req.setAttribute("message","修改密码成功，请退出，使用新密码登录");
//                密码修改成功，移除当前session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("message","修改密码失败");
            }
        }else {
            req.setAttribute("message","新密码有问题");
        }
        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
    }

//实习servlet复用
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
//        从session中拿id
        Object object = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");

        boolean flag =false;
        if (object !=null && newpassword != null){
//使用工具类容易出问题            !StringUtils.isNullOrEmpty(newpassword)
            UserServiceImpl userService = new UserServiceImpl();
            flag = userService.updatePwd(((User)object).getId(),newpassword);

            if (flag){
                req.setAttribute("message","修改密码成功，请退出，使用新密码登录");
//                密码修改成功，移除当前session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("message","修改密码失败");
            }
        }else {
            req.setAttribute("message","新密码有问题");
        }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


//验证旧密码，session中有用户的密码
    public void pwdmodify(HttpServletRequest req, HttpServletResponse resp){
        //        从session中拿id
        Object object = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

//        万能的MAP：结果集
        Map<String,String> resultMap = new HashMap<String, String>();
        if (object == null){//session失效了，session过期了
            resultMap.put("result","sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)){//输入的密码为空
            resultMap.put("result","error");
        }else {
            String userPassword = ((User)object).getUserPassword();//session中用户密码
            if (oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false");
            }
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();

//        JSONArray 阿里巴巴的json工具类，转换格式
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

//重点，难点
    public void query(HttpServletRequest req, HttpServletResponse resp){

//        查询用户列表

//        从前端获取数据
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;

//        获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;
//        第一次走这个请求，一点是第一页，页面大小固定
        int pageSize = 5;//可以把这个写到配置文件中，方便后期修改
        int currentPageNo = 1;

        if (queryUserName == null){
            queryUserName = "";
        }
        if (temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp); //给查询赋值！0,1,2,3
        }
        if (pageIndex != null){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户总数(分页:  上一页，下一页）
        int totalCount = userService.getUserCount(queryUserName,queryUserRole);
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = pageSupport.getTotalPageCount();
        //控制首页和尾页
//        如果页面小于一，就显示第一页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if (currentPageNo > totalPageCount){ //当前页面大于最后一页
            currentPageNo = totalPageCount;
        }

//        获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList",userList);

        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);

        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);

         //  System.out.println(userList);
//        System.out.println(roleList);
//        System.out.println(totalCount);
//        System.out.println(currentPageNo);
//        System.out.println(totalPageCount);
//        System.out.println(queryUserName);
//        System.out.println(queryUserRole);


//        返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
